package com.lushuan.ch11_springboot_test.demo.threadpool;

import java.util.concurrent.*;

public class SingleThreadExecutorExample {

    public static ExecutorService newSingleThreadExecutor() {
        return new ThreadPoolExecutor(
                1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>()
        ) {
            // 确保在 shutdown 之后不再接受新任务
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                if (t != null && !(t instanceof CancellationException)) {
                    // 处理异常
                    t.printStackTrace();
                }
            }

            @Override
            protected void terminated() {
                super.terminated();
                // 清理资源
                System.out.println("ThreadPool has been terminated.");
            }
        };
    }

    public static void main(String[] args) {
        ExecutorService executor = newSingleThreadExecutor();

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println("Task " + taskId + " is running by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 关闭线程池
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}
